export const initShader = (
  gl: WebGLRenderingContext,
  VERTEX_SHADER_SOURCE: string,
  FRAGMENT_SHADER_SOURCE: string
) => {
  // 创建顶点着色器
  const vertexShader = gl.createShader(gl.VERTEX_SHADER) as WebGLShader;
  // 创建片元着色器
  const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER) as WebGLShader;

  // 传入着色器源码
  gl.shaderSource(vertexShader, VERTEX_SHADER_SOURCE);
  gl.shaderSource(fragmentShader, FRAGMENT_SHADER_SOURCE);

  // 编译着色器
  gl.compileShader(vertexShader);
  gl.compileShader(fragmentShader);

  // 创建程序对象
  const program = gl.createProgram() as WebGLProgram;

  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);

  gl.linkProgram(program);
  gl.useProgram(program);

  return program;
};

export const createShader = (
  gl: WebGLRenderingContext,
  type: GLenum,
  source: string
): WebGLShader | undefined => {
  let shader = gl.createShader(type);
  if (shader) {
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (success) return shader;

    console.log(gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
  }
};

export const createProgram = (
  gl: WebGLRenderingContext,
  vertexShader: WebGLShader,
  fragmentShader: WebGLShader
): WebGLProgram | undefined => {
  let program = gl.createProgram();
  if (program) {
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);

    let success = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (success) return program;

    console.log(gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
  }
};
